import Vue from 'vue'
import VueRouter from 'vue-router'
import '@/utils/vant-ui'

const Layout = () => import('@/views/layout/index.vue')
const Search = () => import('@/views/search')
const SearchList = () => import('@/views/search/list')
const ProDetail = () => import('@/views/prodetail')
const Login = () => import('@/views/login')
const Pay = () => import('@/views/pay')
const MyOrder = () => import('@/views/myorder')
const Address = () => import('@/views/address/address.vue')
const AddressEdit = () => import('@/views/address/editAddress')

import Home from '@/views/layout/home'
import Category from '@/views/layout/category'
import Cart from '@/views/layout/cart'
import User from '@/views/layout/user'



// 导入store 注意路径'@/store'
import store from '@/store'
Vue.use(VueRouter)

const routes = [
  { path: '/login', component: Login },
  {
    path: '/', component: Layout,
    redirect: '/home',
    children: [
      {
        path: 'home',
        component: Home
      },
      {
        path: 'category',
        component: Category
      },
      {
        path: 'cart',
        component: Cart
      },
      {
        path: 'user',
        component: User
      }
    ]
  },
  { path: '/search', component: Search },
  { path: '/searchlist', component: SearchList },
  { path: '/prodetail/:id', component: ProDetail },
  { path: '/pay', component: Pay },
  { path: '/myorder', component: MyOrder },
  { path: '/address', component: Address },
  { path: '/editaddress', component: AddressEdit }
]

const router = new VueRouter({
  routes
})

// 全局前置守卫
const authUrl = ['/pay', '/myorder']
router.beforeEach((to, from, next) => {
  // to and from are both route objects. must call `next`.
  if (!authUrl.includes(to.path)) {
    next()
    return
  }
  const token = store.state.user.userInfo.token

  if (token) {
    next()
  } else {
    next('/login')
  }
})
export default router
